<?php

/**
 * 步骤：
 * 从 https://packagist.org/packages搜索下载 firebase/php-jwt
 * composer require firebase/php-jwt
 */
include_once './vendor/autoload.php'; 
use Firebase\JWT\JWT;
 
/**
 * 公钥和私钥生成的方式：Linux 安装openssl扩展
 * openssl genrsa -out rsa_private_key.pem 1024（私钥长度）  生成私钥
 * openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem   生成公钥<
 */

$privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDEHuyngkKAdX9zzgQ7gIBOqAyI5YrJ3MNoH4yklfuVrjKUoY5i
oVBsJFw9RZvSwsk/1QIZkzP4tcszh7tYPURlLZ4jOimr3xMPvdRsaBCgOEy85Wwc
0Zn7wlWAAMufChG8YQvzYDydWwDycQM1PKZAd6wPp3MPP7O0pQtaji5gAQIDAQAB
AoGAc7iDjztvHfk2oRA4sxtZmg/ShZxbzkxzCKdFB4BwGJvWwJirOUtR9t1lh8ng
7fV9Ziq7uHeBPQmXwuoeAyzzg21UtpDY82WgLPOnNtDOz7Wzr6Zj79f/zOHHqDUr
ywaKMAGjHkGsr92gNsN0/ZczweyJ+gumpnmCosy3pTXGIAECQQD+qmrNyPNFBKQn
1rjYw6m9N1ZQH9t+9l6DHgODia9jv6AlbKX8C/VStzcG+kUjmFJ6xbR5edaonbpE
ZSZRCDBBAkEAxSX7JNFJuWYX4dtCrGDwXEOqmQjLaz3o/0NIjjtGZcQ8zhdx5xcN
hEhF6MWoRK9wmdLjn2lJHOkrx/kdaqI/wQJBAJk44a/U0wFYrIfHukm5V7wfuk/V
CxRVmUHcYhLXWW5zkiBSQX/nlf/hejs5gzXKZP23TEG2W7/xvmt+TFJ+0cECQDsX
DjZT0HAUTJYyfMJj78cHtQtXWnkTPlG8HfQbihcYgU0YM9iazT9X1jRVggDMQMiq
L/VovjQ/IxM19H4wkUECQBtIOySFQJvYNdLBT9qvsV23wlh0A3kOVhDKNYfGOXCx
GI6d8XCyyuQasK+yCyCecR8qRSmsUdTzEgBpF3c5iU4=
-----END RSA PRIVATE KEY-----
EOD;

$publicKey = <<<EOD
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEHuyngkKAdX9zzgQ7gIBOqAyI
5YrJ3MNoH4yklfuVrjKUoY5ioVBsJFw9RZvSwsk/1QIZkzP4tcszh7tYPURlLZ4j
Oimr3xMPvdRsaBCgOEy85Wwc0Zn7wlWAAMufChG8YQvzYDydWwDycQM1PKZAd6wP
p3MPP7O0pQtaji5gAQIDAQAB
-----END PUBLIC KEY-----
EOD;

$payload = array(
    "iss" => "example.org",
    "aud" => "example.com",
    "iat" => 1356999524,
    "nbf" => 1357000000
);

$jwt = JWT::encode($payload, $privateKey, 'RS256');
echo "Encode:\n" . print_r($jwt, true) . "\n";

$decoded = JWT::decode($jwt, $publicKey, array('RS256'));

/*
 NOTE: This will now be an object instead of an associative array. To get
 an associative array, you will need to cast it as such:
*/

$decoded_array = (array) $decoded;
echo "Decode:\n" . print_r($decoded_array, true) . "\n";
